/**
 * Copyright 2011 Christian Padovano
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package it.sijom.adapter.impl;

import it.sijom.adapter.IDataAdapter;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * Main Adapter Class . It defines the chain of command for the adapters.
 * Each Adapter defined can handle one type of data conversion
 * @author christian.padovano
 *
 */
public class DataAdapter  {
	
	//list of adapter
	protected List<IDataAdapter> chainOfAdapter;
	
	private final IDataAdapter terminalNodechain= new SimpleCopyAdapter();
	
	/**
	 * Base costructor . Build the JOM default chain of adapter for the data mapping
	 */
	public DataAdapter() {
		chainOfAdapter=new ArrayList<IDataAdapter>();
		chainOfAdapter.add(new Date2CalendarAdapter());
		chainOfAdapter.add(new Calendar2DateAdapter());
		chainOfAdapter.add(new Date2XMLGregorianCalendar());
		chainOfAdapter.add(new XMLGregoriaCalendar2DateAdapter());
		chainOfAdapter.add(new Date2StringAdapter());
		chainOfAdapter.add(terminalNodechain);
	}
	

	/**
	 * Copy the specified attribute called 'attributeName' from the source to target applying some conversion operation
	 * @param source source object
	 * @param target target object
	 * @param attributeName attribute name to copy
	 * @return the target isntance of the object
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException
	 */
	public void copy(Object source, Object target, String attributeName)
			throws InstantiationException, IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		
		for (IDataAdapter adapter : chainOfAdapter) {
			if (adapter.check(source, target, attributeName)) {
		      adapter.copy(source, target, attributeName);
		      break;
			}
		}
		

	}
	
	/**
	 * add a custom adapter to the JOM Default list
	 * @param adapter isntance of the adapter
	 */
	public void addAdapter(IDataAdapter adapter) {
		this.chainOfAdapter.remove(terminalNodechain);
		this.chainOfAdapter.add(adapter);
		this.chainOfAdapter.add(terminalNodechain);
	}

	

}
